package top.dimples.utils;

import top.dimples.model.Prize;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Dimples_Yj
 * @package top.dimples.utils
 * @date 2021/12/18
 */
public class BigWheelDrawUtil {

    /**
     * 生成奖项
     *
     * @return 中奖项的索引
     */
    public static int lottery(List<Prize> prizeList) {

        List<BigDecimal> originalRates = prizeList.stream().map(Prize::getProbability).collect(Collectors.toList());

        if (originalRates.isEmpty()) {
            return -1;
        }

        int size = originalRates.size();

        // 计算总概率，这样可以保证不一定总概率是1
        BigDecimal sumRate = BigDecimal.ZERO;
        for (BigDecimal rate : originalRates) {
            sumRate = sumRate.add(rate);
        }

        // 计sortOriginalRates
        List<BigDecimal> sortOrignalRates = new ArrayList<>(size);
        BigDecimal tempSumRate = BigDecimal.ZERO;
        for (BigDecimal rate : originalRates) {
            tempSumRate = tempSumRate.add(rate);
            sortOrignalRates.add(tempSumRate.divide(sumRate,3, RoundingMode.HALF_UP));
        }
        // 根据区块值来获取抽取到的物品索引
        BigDecimal nextDouble = BigDecimal.valueOf(Math.random());
        sortOrignalRates.add(nextDouble);
        Collections.sort(sortOrignalRates);
        return sortOrignalRates.indexOf(nextDouble);
    }
}
